題目:
找出字串中不含重複字元的最長子字串長度
範例:
兒Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3. Note that "bca" and "cab" are also correct answers.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
想法:
典型解法:滑動視窗 + 雙指標
程式碼:
import java.util.HashMap;
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int maxLen = 0;
int left = 0; // 視窗左邊界
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
// 如果字元重複且在目前視窗內
if (map.containsKey(c) && map.get(c) >= left) {
// 將左邊界移到重複字元的下一個位置
left = map.get(c) + 1;
}
map.put(c, right); // 更新字元最新出現位置
maxLen = Math.max(maxLen, right - left + 1); // 更新最大長度
}
return maxLen;
}
}
實際操作:
字串:"p w w k e w"
索引: 0 1 2 3 4 5
Step1:
right = 0 → p
Step2:
right = 1 → w
Step3:
right = 2 → w(重複)
Step4:
right = 3 → k
Step5:
right = 4 → e
Step6:
right = 5 → w(重複)
結果:maxLen = 3